import axios from "axios";
import {
	ElMessage
} from 'element-plus'

const service = axios.create({
	baseURL: "http://localhost:8099/",
	// baseURL: "http://8.134.160.39:8099/",
	timeout: 0,
	headers: {
		"Content-Type": "application/json;charset=utf-8",
		"Access-Control-Allow-Origin": "*",
		"error-message": ''
	}
})
//响应拦截器
service.interceptors.request.use(
	config => {
		var token = window.sessionStorage.getItem("token");
		var user  = JSON.parse(window.sessionStorage.getItem("user"));

		if (token) {
			config.headers["X-TOKEN"] = token
			if (user.account=='showAccount'){
				config.headers["X-SHOW"]="show"
			}
		} else {
			config.headers["X-TOKEN"] = ""
			config.headers["X-SHOW"]=""
		}
		return config;
	},
	error => {
		console.log("request.error------:", error)
		return Promise.resolve(error)
	}
);

service.interceptors.response.use(
	response => {
		console.log("response------:", response.data)
		if (response.data.code == '403.1') {
			window.sessionStorage.removeItem("token");
			window.sessionStorage.removeItem("user");
			ElMessage.error("错误码——————>" + response.data.code + "\t\t报错信息——————>" + response.data.message)
		}
		if (response.data.code != '200' && response.data.code != '' && response.data.code != undefined) {
			// 状态码不为200，可能存在某些报错！
			ElMessage.error("错误码——————>" + response.data.code + "\t\t报错信息——————>" + response.data.message)
		}
		return response.data;
	},
	error => {
		console.log("response.error------:", error)

		var checkMessage = error.response.headers['error-message']

		if (checkMessage) {
			if (error.response.status == '403') {
				console.log("response.error------:", error)
				alert("错误码：" + error.response.status + "\t错误信息：" + checkMessage + "，请重新登录", )
				window.sessionStorage.removeItem("token")
				window.location.href = '/'
			}
			if (error.response.status == '500') {
				// console.log("进入500判断")
				if (checkMessage == '' || checkMessage == undefined ) {

					ElMessage.error("未知错误！请检查后台！")
				} else {
					ElMessage.error("出现错误：" + checkMessage)
				}
			}
			if (error.response.status == '403.1') {
				config.headers["X-TOKEN"] = ""
				window.sessionStorage.removeItem("token");
			}
		}
		if (error.response.status=='404'){
			window.location.href="/common/error"
		}
		return Promise.resolve(error);
	}
);
export default service;
